/******************************************************************
 * Copyright (c) 2025 Bocloud Technologies Co., Ltd.
 * installer is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain n copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 ******************************************************************/

package utils

import (
	"archive/tar"
	"compress/gzip"
	"io"
	"os"
	"path/filepath"
	"strings"

	goutils "go-frpc/utils"

	"gopkg.openfuyao.cn/bkeadm/utils/log"
)

// Tar 将 src 目录打包成 tar.gz 压缩包，dst 为压缩包的保存路径
func Tar(src, dst string, absolute bool) error {
	// 创建文件
	fw, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer fw.Close()

	// 使用 gzip 压缩
	gw := gzip.NewWriter(fw)
	defer gw.Close()

	// 创建 Tar.Writer 结构
	tw := tar.NewWriter(gw)
	defer tw.Close()

	// 递归处理目录及目录下的所有文件和目录
	return filepath.Walk(src, func(fileName string, fi os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		ftr, err := tar.FileInfoHeader(fi, "")
		if err != nil {
			return err
		}

		name := fileName
		if !absolute {
			name = strings.TrimPrefix(fileName, src)
		}
		ftr.Name = strings.TrimPrefix(name, string(filepath.Separator))

		if err := tw.WriteHeader(ftr); err != nil {
			return err
		}

		if !fi.Mode().IsRegular() {
			return nil
		}

		fr, err := os.Open(fileName)
		if err != nil {
			return err
		}
		defer fr.Close()

		n, err := io.Copy(tw, fr)
		if err != nil {
			return err
		}

		log.Debugf("Package %s successfully, write %d bytes of data\n", fileName, n)
		return nil
	})
}

// UnTar extracts a tar archive to the specified destination directory
func UnTar(src, dst string) error {
	return goutils.UnTar(src, dst, false)
}
